package com.service;


import com.dao.DepDAO;
import com.pojo.Dep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepService {

    @Autowired
    private DepDAO depDAO;

    /**
     * 查所有部门
     * @return
     */
    public List findAll1()
    {
        List list = depDAO.findAll();
        return list;
    }

    /**
     * 查所有部门，结果按编号序列
     * @return
     */
    public List  findAll2()
    {
        Sort sort = Sort.by(Sort.Order.desc("depId"));
        List list = depDAO.findAll(sort);
        return list;
    }

    /**
     *  根据部门名称查询，结果分页
     * @param depName
     * @param page
     * @param size
     * @return
     */
    public Page findAllByDepname(String depName,int page, int size)
    {    //depDAO.findAll   查所有部门
         //depDAO.findAll(Example)  按条件查所有部门，不分页
         //depDAO.findAll(Example, Pageable) 按条件查，分页
         //depDAO.findAll(Specification, Pageable); 按动态条件查，分页
        //要查询的值
        Dep dep = new Dep();
        dep.setDepName("国");

        //值的匹配
        ExampleMatcher  exampleMatcher = ExampleMatcher.matching().withMatcher("depName",ExampleMatcher.GenericPropertyMatchers.startsWith() );
        Example e = Example.of(dep,exampleMatcher);

        //分页
        Pageable pageable =  PageRequest.of(page,size);
        //System.out.println(depDAO.findAll(e));
        return depDAO.findAll(e,pageable);



    }

    /**
     * 条件搜索且分页
     * @param depId  编号
     * @param depName 名称
     * @param page  第几页
     * @param size  页大小
     * @return
     */
    public Page search(Integer depId, String depName, int page, int size)
    {
        Pageable  pageable = PageRequest.of(page,size);


        List paramList = new ArrayList();
        Specification<Dep>   specification = new Specification<Dep>() {
            @Override
            public Predicate toPredicate(Root<Dep> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                if (depId!=null)
                {
                    paramList.add( cb.equal(root.get("depId"),depId) ); // where depId=depId
                }
                if (depName!=null &&depName.length()>0)
                {
                    paramList.add( cb.like(root.get("depName"),"%"+depName+"%") );//   where depName like
                }
                Predicate[] predicates = new Predicate[paramList.size()];
                paramList.toArray(predicates);

                return cb.and(predicates);
            }
        };
       return null;
       //return depDAO.findAll(specification, pageable);
    }
}
